﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;


namespace GoPlay.Models
{
    public class GoPlayDbContext : DbContext
    {
        public GoPlayDbContext()
            : base("GoPlayDB")
        { }

        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet Membership { get; set; }
        public DbSet Roles { get; set; }
        public DbSet OAuthMembership { get; set; }
        public DbSet<Team> Teams { get; set; }
        public DbSet<Contact> Contacts { get; set; }
        public DbSet<Game> Games { get; set; }
        public DbSet<Player> Players { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Membership>()
                .HasMany<Role>(r => r.Roles)
                .WithMany(u => u.Members)
                .Map(m =>
                {
                    m.ToTable("webpages_UsersInRoles");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("RoleId");
                });

            modelBuilder.Entity<Team>().ToTable("Teams");
            modelBuilder.Entity<Contact>().ToTable("Contacts");
            modelBuilder.Entity<Game>().ToTable("Games");
            modelBuilder.Entity<Player>().ToTable("Players");

            ////modelBuilder.Entity<Child>()
            ////.HasRequired(c => c.Parent)
            ////.WithMany(p => p.Childs)
            ////.HasForeignKey(c => c.ParentId);

            modelBuilder.Entity<Game>()
            .HasRequired(t => t.Team)
            .WithMany(t => t.Games)
            .HasForeignKey(t => t.TeamId)
            .WillCascadeOnDelete(false);

            modelBuilder.Entity<Game>()
            .HasKey(c => new { c.Id, c.TeamId });

            modelBuilder.Entity<Game>()
            .Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);



            modelBuilder.Entity<Player>()
            .HasKey(c => new { c.Id, c.TeamId });

            modelBuilder.Entity<Player>()
            .Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            modelBuilder.Entity<Player>()
            .HasRequired(t => t.Team)
            .WithMany(t => t.Players)
            .HasForeignKey(t => t.TeamId)
            .WillCascadeOnDelete(false);

            modelBuilder.Entity<Player>()
            .HasRequired(t => t.Contact)
            .WithMany()
            .HasForeignKey(t => t.ContactId)
            .WillCascadeOnDelete(false);
        }
    }
}